package com.emm.yixun.customer.service.impl.app.manage;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.emm.yixun.common.app.EditCustomerIntentionReqDto;
import com.emm.yixun.customer.service.CustomerServiceFacade;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.basic.mapper.CustomerMapper;
import com.emm.yixun.basic.service.BaseCodeValueService;
import com.emm.yixun.basic.service.BusinessRelationService;
import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.FamilyMemberService;
import com.emm.yixun.common.app.EditCustomerReqDto;
import com.emm.yixun.common.app.base.CommonResDTO;
import com.emm.yixun.common.app.servletentity.FamilyMemberListReq;
import com.emm.yixun.common.enums.ResultEnum;
import com.emm.yixun.common.model.BaseCodeValue;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.FamilyMember;
import com.emm.yixun.common.model.dto.BaseCodeValueDto;
import com.emm.yixun.common.model.dto.BusinessRelationDto;
import com.emm.yixun.common.model.dto.CustomerDto;
import com.emm.yixun.common.model.dto.FamilyMemberDto;
import com.emm.yixun.common.model.enums.CustomerStatusEnum;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.MemberTypeEnum;
import com.emm.yixun.common.model.enums.RelationTypeEnum;
import com.emm.yixun.common.model.enums.SexEnum;

@Service("editCustomerManage")
public class EditCustomerManage {

	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private BusinessRelationService businessRelationService;
	
	@Autowired
	private FamilyMemberService familyMemberService;
	
	@Autowired
	private CustomerMapper customerMapper;
	
	@Autowired
	private BaseCodeValueService baseCodeValueService;
	@Autowired
	private AddCustomerManage addCustomerManage;
	@Autowired
	private CustomerServiceFacade customerServiceFacade;
	
	/**
	 * 修改客户基本信息
	 * @param reqDto
	 * @return
	 */
	public CommonResDTO editCustomer(EditCustomerReqDto reqDto) {
		CustomerDto customerDto = new CustomerDto();
		BeanUtils.copyProperties(reqDto, customerDto);
		CommonResDTO resDto = new CommonResDTO();
		try {
			//修改客户信息时，只允许修改首次沟通内容
//			customerDto.setFtContactWay(null);
//			customerDto.setFtContactTime(null);
//			customerDto.setFtContactWay1(null);
//			customerDto.setFtContactTime1(null);
			if(StringUtils.isNotEmpty(customerDto.getFtContactWay())){
				customerDto.setFtContactWay1(customerDto.getFtContactWay());
			}

			if(customerDto.getFtContactTime() != null){
				customerDto.setFtContactTime1(customerDto.getFtContactTime());
			}
			if(StringUtils.isNotEmpty(customerDto.getFtContactContent())){
				customerDto.setFtContactContent1(customerDto.getFtContactContent());
			}

			customerDto.setPePostcode(reqDto.getPePostcode()+"");
			customerDto.setUpdateUserId(Long.parseLong(reqDto.getUserId()));
			customerDto.setId(Long.valueOf(reqDto.getCustomerId()));
			customerDto.setUpdateTime(new Date());
			if(reqDto.getQqNum() != null){
				customerDto.setQqNumber(reqDto.getQqNum());
			}
			if(reqDto.getIndustry() != null){
				customerDto.setCongshihangye(reqDto.getIndustry());
			}
			if(reqDto.getNatureCompany() != null){
				customerDto.setCompanyXingzhi(reqDto.getNatureCompany());
			}
			if(reqDto.getAnnualTurnoverCompany() != null){
				customerDto.setCompanyYingye(reqDto.getAnnualTurnoverCompany());
			}
			if(reqDto.getFamilyStructure() != null){
				customerDto.setFamilyJie(reqDto.getFamilyStructure());
			}
			if(reqDto.getIsEmployees() != null){
				customerDto.setIsYuangong(reqDto.getIsEmployees());
			}
			if(reqDto.getIsOwnerCompany() != null){
				customerDto.setIsYezhu(reqDto.getIsOwnerCompany());
			}
			if(reqDto.getIsLiveElderly() != null){
				customerDto.setIsLaoren(reqDto.getIsLiveElderly());
			}
			if(reqDto.getIsChildren() != null){
				customerDto.setIsZinv(reqDto.getIsChildren());
			}
			if(reqDto.getIntentionPropertyType() != null){
				customerDto.setYixiangwuyeType(reqDto.getIntentionPropertyType());
			}
			if(reqDto.getBuyParking() != null){
				customerDto.setBuyCar(reqDto.getBuyParking());
			}
			//日常信息获取途径
			if(reqDto.getDailyInformation() != null  && !"".equals(reqDto.getDailyInformation())  && !"null".equals(reqDto.getDailyInformation())){
				customerDto.setRichangxinxi(reqDto.getDailyInformation());
			}else{
				customerDto.setRichangxinxi("");
			}
			//客户初始状态
			if(reqDto.getCustomerStatus() != null){
				customerDto.setCustomerStatusBk(reqDto.getCustomerStatus());
			}
			customerMapper.editCus(customerDto);

			customerServiceFacade.changeCustomerPerfect(customerDto.getId());
			/**
			 * 20190307判断A级客户是否已填完信息
			 * app端bug，由于无移动端开发人员，因此暂时在后端处理
			 * junze.liu 
			 */
			if("2".equals(customerDto.getIntentionLevel())) {
				isIntentionIntact(customerDto.getId());
			}

			//比较字段变更差异
			//获取变更前记录
			Customer original = customerService.selectById(customerDto.getId());
			CustomerDto originalDto = new CustomerDto();
			if(null != original){
				BeanUtils.copyProperties(original, originalDto);
			}
			addCustomerManage.compareCustomer(originalDto, customerDto, "UPDATE", reqDto.getUserId());

		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("修改客户信息失败!");
			resDto.setResult("0");
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	/**
	 * 修改客户基本信息
	 * @param reqDto
	 * @return
	 */
	public CommonResDTO editCustomer(EditCustomerIntentionReqDto reqDto) {
		CustomerDto customerDto = new CustomerDto();
		BeanUtils.copyProperties(reqDto, customerDto);
		CommonResDTO resDto = new CommonResDTO();
		try {
			//修改客户信息时，只允许修改首次沟通内容
//			customerDto.setFtContactWay(null);
//			customerDto.setFtContactTime(null);
//			customerDto.setFtContactWay1(null);
//			customerDto.setFtContactTime1(null);

			if(StringUtils.isNotEmpty(customerDto.getFtContactWay())){
				customerDto.setFtContactWay1(customerDto.getFtContactWay());
			}

			if(customerDto.getFtContactTime() != null){
				customerDto.setFtContactTime1(customerDto.getFtContactTime());
			}
			if(StringUtils.isNotEmpty(customerDto.getFtContactContent())){
				customerDto.setFtContactContent1(customerDto.getFtContactContent());
			}

			//判断客户状态是来访还是来电
			BaseCodeValue bvc = getBaseCodeValue(customerDto.getProjectId(), "来电");
			if(null != reqDto.getFtContactWay() && !reqDto.getFtContactWay().equals(bvc.getId().toString())) {
				//客户状态为来电
				customerDto.setCustomerStatus(CustomerStatusEnum.VISIT.getNo());
			} else {
				//客户状态为来访
				customerDto.setCustomerStatus(CustomerStatusEnum.CALL.getNo());
			}
			
			customerDto.setPePostcode(reqDto.getPePostcode()+"");
			customerDto.setUpdateUserId(Long.parseLong(reqDto.getUserId()));
			customerDto.setId(Long.valueOf(reqDto.getCustomerId()));
			customerDto.setUpdateTime(new Date());
			if(reqDto.getQqNum() != null){
				customerDto.setQqNumber(reqDto.getQqNum());
			}
			if(reqDto.getIndustry() != null){
				customerDto.setCongshihangye(reqDto.getIndustry());
			}
			if(reqDto.getNatureCompany() != null){
				customerDto.setCompanyXingzhi(reqDto.getNatureCompany());
			}
			if(reqDto.getAnnualTurnoverCompany() != null){
				customerDto.setCompanyYingye(reqDto.getAnnualTurnoverCompany());
			}
			if(reqDto.getFamilyStructure() != null){
				customerDto.setFamilyJie(reqDto.getFamilyStructure());
			}
			if(reqDto.getIsEmployees() != null){
				customerDto.setIsYuangong(reqDto.getIsEmployees());
			}
			if(reqDto.getIsOwnerCompany() != null){
				customerDto.setIsYezhu(reqDto.getIsOwnerCompany());
			}
			if(reqDto.getIsLiveElderly() != null){
				customerDto.setIsLaoren(reqDto.getIsLiveElderly());
			}
			if(reqDto.getIsChildren() != null){
				customerDto.setIsZinv(reqDto.getIsChildren());
			}
			if(reqDto.getIntentionPropertyType() != null){
				customerDto.setYixiangwuyeType(reqDto.getIntentionPropertyType());
			}
			if(reqDto.getBuyParking() != null){
				customerDto.setBuyCar(reqDto.getBuyParking());
			}
			//日常信息获取途径
			if(reqDto.getDailyInformation() != null  && !"".equals(reqDto.getDailyInformation())  && !"null".equals(reqDto.getDailyInformation())){
				customerDto.setRichangxinxi(reqDto.getDailyInformation());
			}else{
				customerDto.setRichangxinxi("");
			}
			//客户初始状态
			if(reqDto.getCustomerStatus() != null){
				customerDto.setCustomerStatusBk(reqDto.getCustomerStatus());
			}
	
			customerMapper.editCus(customerDto);
			customerServiceFacade.changeCustomerPerfect(Long.valueOf(reqDto.getCustomerId()));

			
			/**
			 * 20190307判断A级客户是否已填完信息
			 * app端bug，由于无移动端开发人员，因此暂时在后端处理
			 * junze.liu 
			 */
			if("2".equals(customerDto.getIntentionLevel())) {
				//isIntentionIntact(customerDto.getId());
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("修改客户信息失败!");
			resDto.setResult("0");
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}
	
	/**
	 * 查询当前项目的基础参数
	 */
	private BaseCodeValue getBaseCodeValue(Long projectId, String codeName) {
		BaseCodeValueDto entity = new BaseCodeValueDto();
		entity.setProjectId(projectId);
		entity.setCodeName(codeName);
		entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
		BaseCodeValue bcv = baseCodeValueService.selectByDto(entity);
		return bcv;
	}
	
	/**
	 * 20190308判断A级客户是否已填完信息
	 * app端bug，由于无移动端开发人员，因此暂时在后端处理
	 * junze.liu 
	 */
	private void isIntentionIntact(Long customerId) {
		Customer customer = customerMapper.selectById(customerId);
		if(customer == null) {
			return;
		}
		//信息是否已填完标识(已填完   = true)
		boolean flag = true;
		//客户姓名
		if(StringUtils.isBlank(customer.getCustomerName())) {
			flag = false;
		}
		//性别
		if(StringUtils.isBlank(customer.getCustomerSex())) {
			flag = false;
		}
		//联系电话
		if(StringUtils.isBlank(customer.getCustomerPhone())) {
			flag = false;
		}
		//意向等级
		if(StringUtils.isBlank(customer.getIntentionLevel())) {
			flag = false;
		}
		//获知途径
		if(StringUtils.isBlank(customer.getInformedWay())) {
			flag = false;
		}
		//首次接触
		if(StringUtils.isBlank(customer.getFtContactWay()) 
				&& customer.getFtContactTime() == null
				&& StringUtils.isBlank(customer.getFtContactContent())) {
			//来电
			flag = false;
		} else if(StringUtils.isBlank(customer.getFtContactWay1()) 
				&& customer.getFtContactTime1() == null
				&& StringUtils.isBlank(customer.getFtContactContent1())) {
			//来访、电转访
			flag = false;
		}
		//置业动机
		if(StringUtils.isBlank(customer.getRqTheirMotives())) {
			flag = false;
		}
		//关注重点
		if(StringUtils.isBlank(customer.getRqFocusId())) {
			flag = false;
		}
		//需求面积
		if(StringUtils.isBlank(customer.getRqDemandArea())) {
			flag = false;
		}
		//付款方式
		if(StringUtils.isBlank(customer.getRqPaymentMethod())) {
			flag = false;
		}
		//生活服务
		if(StringUtils.isBlank(customer.getRqPaymentMethod())) {
			flag = false;
		}
		//居住区
		if(customer.getPeResidenceProvinceId() == null
				|| customer.getPeResidenceCityId() == null
				|| customer.getPeResidenceAreaId() == null) {
			flag = false;
		}
		//工作区
		if(customer.getPeWorkaroundProvinceId() == null
				|| customer.getPeWorkaroundCityId() == null
				|| customer.getPeWorkaroundAreaId() == null) {
			flag = false;
		}
		//从事行业
		if(StringUtils.isBlank(customer.getCongshihangye())) {
			flag = false;
		}
		//更新状态@
		Customer entity = new Customer();
		entity.setId(customerId);
		if(flag) {
			//已填完
			entity.setIsIntentionIntact("1");
		} else {
			//未填完
			entity.setIsIntentionIntact("0");
		}
		customerMapper.editCus(entity);
	}
	
	/**
	 * 修改客户关注户型
	 * @param houseTypeList 关注户型列表
	 * @return 
	 */
	public CommonResDTO editCusHouseTypeFocus(Customer customer, List<String> houseTypeList){
		CommonResDTO resDto = new CommonResDTO();
		try {
			//删除客户关注户型,修改del_flag = 1
			BusinessRelationDto brDto = new BusinessRelationDto();
			brDto.setSingleId(customer.getId());
			brDto.setProjectCode(customer.getProjectCode());
			brDto.setRelationType(RelationTypeEnum.HOUSE_TYPE.getNo());
			businessRelationService.destroy(brDto);
			//添加新的关注户型
			for (String houseType: houseTypeList) {
				JSONObject object = JSONObject.parseObject(houseType);
				long houseTypeId = object.getLongValue("houseTypeId");
				brDto = new BusinessRelationDto();
				brDto.setProjectId(customer.getProjectId());
				brDto.setProjectCode(customer.getProjectCode());
				brDto.setSingleId(customer.getId());
				brDto.setRelationType(RelationTypeEnum.HOUSE_TYPE.getNo());
				brDto.setMoreId(houseTypeId);
				brDto.setMerchantId(customer.getMerchantId());
				brDto.setUserCode(customer.getUserCode());
				brDto.setAccessCode(customer.getAccessCode());
				brDto.setCreateUserId(customer.getCreateUserId());
				brDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				brDto.setRemark("客户关注户型");
				businessRelationService.create(brDto);
			}
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("修改客户关注户型失败!");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}
	
	/**
	 * 修改客户关注组团(楼盘)
	 * 
	 * @param customer 客户信息
	 * @param premisesList 关注户型列表
	 * @return 
	 */
	public CommonResDTO editCusPremisesFocus(Customer customer, List<String> premisesList){
		CommonResDTO resDto = new CommonResDTO();
		try {
			//删除客户关注房号,修改del_flag = 1
			BusinessRelationDto brDto = new BusinessRelationDto();
			brDto.setSingleId(customer.getId());
			brDto.setProjectCode(customer.getProjectCode());
			brDto.setRelationType(RelationTypeEnum.PREMISES.getNo());
			businessRelationService.destroy(brDto);
			//添加新的关注组团(楼盘)
			for (String premises: premisesList) {
				if(StringUtils.isEmpty(premises)){
					continue;
				}
				JSONObject object = JSONObject.parseObject(premises);
				long premisesId = object.getLongValue("premisesId");
				brDto = new BusinessRelationDto();
				brDto.setProjectId(customer.getProjectId());
				brDto.setProjectCode(customer.getProjectCode());
				brDto.setSingleId(customer.getId());
				brDto.setRelationType(RelationTypeEnum.PREMISES.getNo());
				brDto.setMoreId(premisesId);
				brDto.setMerchantId(customer.getMerchantId());
				brDto.setUserCode(customer.getUserCode());
				brDto.setAccessCode(customer.getAccessCode());
				brDto.setCreateUserId(customer.getCreateUserId());
				brDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				brDto.setRemark("客户意向组团");
				businessRelationService.create(brDto);
			}
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("修改客户意向组团失败!");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}
	
	/**
	 * 修改客户关注房号
	 * 
	 * @param customer 客户信息
	 * @param roomList 关注房号列表
	 * @return 
	 */
	public CommonResDTO editCusRoomFocus(Customer customer, List<String> roomList){
		CommonResDTO resDto = new CommonResDTO();
		try {
			//删除客户关注房号,修改del_flag = 1
			BusinessRelationDto brDto = new BusinessRelationDto();
			brDto.setSingleId(customer.getId());
			brDto.setProjectCode(customer.getProjectCode());
			brDto.setRelationType(RelationTypeEnum.ROOM.getNo());
			businessRelationService.destroy(brDto);
			//添加新的关注房号
			for (String room: roomList) {
				JSONObject object = JSONObject.parseObject(room);
				long roomId = object.getLongValue("roomId");
				brDto = new BusinessRelationDto();
				brDto.setProjectId(customer.getProjectId());
				brDto.setProjectCode(customer.getProjectCode());
				brDto.setSingleId(customer.getId());
				brDto.setRelationType(RelationTypeEnum.ROOM.getNo());
				brDto.setMoreId(roomId);
				brDto.setMerchantId(customer.getMerchantId());
				brDto.setUserCode(customer.getUserCode());
				brDto.setAccessCode(customer.getAccessCode());
				brDto.setCreateUserId(customer.getCreateUserId());
				brDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				brDto.setRemark("客户关注房号");
				businessRelationService.create(brDto);
			}
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("修改客户关注房号失败!");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}
	
	/**
	 * 修改客户家庭成员
	 * 
	 * @param customer 客户信息
	 * @param familyMemberList 关注房号列表
	 * @return 
	 */
	public CommonResDTO editCusFamily(Customer customer, List<FamilyMemberListReq> familyMemberList){
		CommonResDTO resDto = new CommonResDTO();
		try {
			FamilyMemberDto fmDto = new FamilyMemberDto();
			//删除客户原有家庭成员,修改del_flag = 1
			FamilyMemberDto familyMemberDto = new FamilyMemberDto();
			familyMemberDto.setCustomerId(customer.getId());
			familyMemberDto.setProjectCode(customer.getProjectCode());
			familyMemberDto.setMemberType(MemberTypeEnum.CUSTOMER_ADD.getNo());
			List<FamilyMember> fmList = familyMemberService.selectListByDto(familyMemberDto);
			if(fmList.size() > 0){
				fmDto.setCustomerId(customer.getId());
				fmDto.setProjectCode(customer.getProjectCode());
				fmDto.setMemberType(MemberTypeEnum.CUSTOMER_ADD.getNo());
				fmDto.setBuyId(customer.getId());
				familyMemberService.destroy(fmDto);
			}
			
			//重新添加家庭成员
			int index = 0;
			for (FamilyMemberListReq family: familyMemberList) {
				if(family != null){
					if(StringUtils.isNotBlank(family.getMemberName()) || StringUtils.isNotBlank(family.getBirthday())){
						String memberName = family.getMemberName();
						String sex = family.getSex();
						String birthday = family.getBirthday();
						String projectCode = null;
						String merchantId = null;
						if(family.getProjectCode() != null){
							projectCode = family.getProjectCode();
						}else{
							projectCode = customer.getProjectCode();
						}
						if(family.getMerchantId() != null){
							merchantId = String.valueOf(family.getMerchantId());
						}else{
							merchantId = String.valueOf(customer.getMerchantId());
						}
						fmDto = new FamilyMemberDto();
						fmDto.setCustomerId(customer.getId());
						fmDto.setProjectId(customer.getProjectId());
						fmDto.setProjectCode(projectCode);
						fmDto.setBuyId(customer.getId());
						if(StringUtils.isNotEmpty(memberName)){
							fmDto.setMemberName(memberName);
						}
						if(sex != null){
							fmDto.setSex(sex);
						}else{
							fmDto.setSex(SexEnum.UNKNOW.getNo());
						}
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
						if(StringUtils.isNotEmpty(birthday)){
							fmDto.setBirthday(sdf.parse(birthday));
						}
						fmDto.setMemberType(MemberTypeEnum.CUSTOMER_ADD.getNo());
						if(index == 0){
							fmDto.setIsDefault("1");
						}else{
							fmDto.setIsDefault("0");
						}
						fmDto.setMerchantId(Long.parseLong(merchantId));
						fmDto.setUserCode(customer.getUserCode());
						fmDto.setAccessCode(customer.getAccessCode());
						fmDto.setCreateUserId(customer.getCreateUserId());
						fmDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
						fmDto.setRemark("添加客户家庭成员");
						familyMemberService.create(fmDto);
						index++;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("修改客户家庭成员失败!");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}
	
}
